﻿using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ESoft.Core.Util.Helpers
{

    public struct PicSize
    {
        public int Width;
        public int Height;
    }


    public class ImageHelper
    {
        public static string GenerateHighThumbnail(string path, int width, int height)
        {
            var pathDir = Path.GetDirectoryName(path);
            pathDir += Path.DirectorySeparatorChar + "scale" + Path.DirectorySeparatorChar + width + "_" + height;
            var newPath = pathDir + Path.DirectorySeparatorChar + Path.GetFileName(path);
            if (File.Exists(newPath))
            {
                return newPath;
            }
            if (!Directory.Exists(pathDir))
            {
                Directory.CreateDirectory(pathDir);
            }
            using (Image<Rgba32> oldImage = Image.Load(path))
            {
                int newWidth = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width;
                int newHeight = AdjustSize(width, height, oldImage.Width, oldImage.Height).Height;

                oldImage.Mutate(x => x
                     .Resize(new ResizeOptions
                     {
                         Size = new Size(width, height),
                         Mode = ResizeMode.Max
                     }));
                oldImage.Save(newPath); // Automatic encoder selected based on extension.
                path = newPath;
            }

            return path;
        }

        public static PicSize AdjustSize(int spcWidth, int spcHeight, int orgWidth, int orgHeight)
        {
            PicSize size = new PicSize();
            // 原始宽高在指定宽高范围内，不作任何处理 
            if (orgWidth <= spcWidth && orgHeight <= spcHeight)
            {
                size.Width = orgWidth;
                size.Height = orgHeight;
            }
            else
            {
                // 取得比例系数 
                float w = orgWidth / (float)spcWidth;
                float h = orgHeight / (float)spcHeight;
                // 宽度比大于高度比 
                if (w > h)
                {
                    size.Width = spcWidth;
                    size.Height = (int)(w >= 1 ? Math.Round(orgHeight / w) : Math.Round(orgHeight * w));
                }
                // 宽度比小于高度比 
                else if (w < h)
                {
                    size.Height = spcHeight;
                    size.Width = (int)(h >= 1 ? Math.Round(orgWidth / h) : Math.Round(orgWidth * h));
                }
                // 宽度比等于高度比 
                else
                {
                    size.Width = spcWidth;
                    size.Height = spcHeight;
                }
            }
            return size;
        }
    }
}
